package com.star.eastern.blee

import android.Manifest
import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGattServer
import android.bluetooth.le.*
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.Intent.*
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Parcel
import android.os.ParcelUuid
import android.support.v7.app.AppCompatActivity
import android.util.Log
import com.star.eastern.blee.utils.Tripple7BluetoothCommandProtocol
import com.star.eastern.blee.utils.activity
import com.tangula.android.base.TglBasicActivity
import com.tangula.android.utils.*
import java.util.*


open class BlueToothActivty : TglBasicActivity() {

    var adapter: BluetoothAdapter?=null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //setContentView(R.layout.activity_blue_tooth_tech_activty)

        PermissionUtils.whenHasAllPremissions(this, listOf(Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN,
            Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION
            ), {
            adapter = BluetoothAdapter.getDefaultAdapter()
            if (adapter == null) {
                onNotSupportedBlueTooth()
            }else {
                //Log.v("console", "support blue tooth")
                if (!adapter!!.isEnabled) {
                    //蓝牙没有打开， bt is't enable
                    val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
                    ActivityResultUtils.startActivityForResult(this, enableBtIntent) {resCode,_->
                        if(resCode==RESULT_OK){
                            onUserEnableBlueToothSuccess(adapter!!)
                        }else if(resCode == RESULT_CANCELED){
                            onUserEnableBlueToothCanceled(adapter!!)
                        }
                    }
                }else{
                    onDeviceReady(adapter!!) //设备就绪
                }
            }
        }, {
            onPermissionsNotGranted()
        })

    }



    //private var stopDiscoveryFunc:(()->Unit)? = null

    fun stopDiscovery(){
        Tripple7BluetoothCommandProtocol.stopScan()
    }
    open fun listBlueToothDeviceSet(onFound:(ScanResult)->Unit): MutableSet<BluetoothDevice> {
        Tripple7BluetoothCommandProtocol.startScan { it-> onFound(it) }
        return mutableSetOf()
    }

    /**
     * List bluetooth devices.
     */
    @SuppressLint("NewApi")
    open fun listBlueToothDeviceSet(adapter: BluetoothAdapter, onFound:(ScanResult)->Unit): MutableSet<BluetoothDevice> {

        return mutableSetOf<BluetoothDevice>().also {


            it.addAll(adapter.bondedDevices)
            /*
            it.forEach{device->
                Log.v("console", "found bonded bt device name=${device.name} address=${device.address}")
            }
            */

            val filter = IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED)
            registerReceiver(object : BroadcastReceiver() {
                override fun onReceive(context: Context, intent: Intent) {
                    val action = intent.action
                    // When discovery finds a device
                    if (BluetoothDevice.ACTION_ACL_DISCONNECTED == action) {
                        // Get the BluetoothDevice object from the Intent
                        val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                        if(device.address==Tripple7BluetoothCommandProtocol.currentDevice?.address?:""){
                            TaskUtils.runInUiThread {
                                activity.switch2BleScanPage()
                            }
                        }
                    }
                }
            }, filter)

            /*
            val filter = IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
            registerReceiver(object : BroadcastReceiver() {
                override fun onReceive(context: Context, intent: Intent) {
                    val action = intent.action
                    // When discovery finds a device
                    if (BluetoothDevice.ACTION_BOND_STATE_CHANGED == action) {
                        // Get the BluetoothDevice object from the Intent
                        val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                        it.add(device)
                        val state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE,-1)
                        val pstate = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, -1)

                        Log.v("console", "${device.address==Tripple7BluetoothCommandProtocol.getDeviceAddress()}, $state, $pstate")

                    }
                }
            }, filter)
            */

            /*
            val filter = IntentFilter(BluetoothDevice.ACTION_FOUND)
            registerReceiver(object : BroadcastReceiver() {
                override fun onReceive(context: Context, intent: Intent) {
                    val action = intent.action
                    // When discovery finds a device
                    if (BluetoothDevice.ACTION_FOUND == action) {
                        // Get the BluetoothDevice object from the Intent
                        val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                        Log.v("console", "discovery a bt device, name=${device.name} address=${device.address}")
                        it.add(device)
                        onFound(device, intent)
                    }
                }
            }.also {
                if(stopDiscoveryFunc!=null){
                    stopDiscovery()
                }
                stopDiscoveryFunc = {
                    adapter.cancelDiscovery()
                    unregisterReceiver(it)
                    stopDiscoveryFunc = null
                }
            }, filter)
            */


            //Log.v("console", "start le scan")
            /*
            adapter.startLeScan{dev, rssi, data->
                    onFound(dev, Intent(), rssi, data)
                }
                */
            Tripple7BluetoothCommandProtocol.startScan(onFound)

            //adapter.startDiscovery()
        }
    }



    protected open fun onDeviceReady(adapter: BluetoothAdapter) {
        //Log.v("console", "Blue Tooth Device is ready")

        /*
        val filter = IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED)
        registerReceiver(object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                val action = intent.action
                // When discovery finds a device
                if (BluetoothDevice.ACTION_ACL_DISCONNECTED == action) {
                   // onBtDisconnected()
                }
            }
        }, filter)
        */

    }

    protected open fun onBtDisconnected(){

    }

    /**
     * 应用没有需要的授权时.
     */
    protected open fun onPermissionsNotGranted() {
        ToastUtils.showToastResLong(R.string.please_grant_permission)
    }

    /**
     * 手机不支持蓝牙设备.
     */
    protected open fun onNotSupportedBlueTooth() {
        Log.v("console", "not supported blue tooth")
        val intent = Intent(this@BlueToothActivty, NoBlueToothActivity::class.java)
        intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
        this.startActivity(intent)
//        ActivityUtils.startActivity(NoBlueToothActivity::class)
    }

    /**
     * 用户没有启用蓝牙设备.
     */
    protected open fun onUserEnableBlueToothCanceled(adapter: BluetoothAdapter) {
        ToastUtils.showToastResLong(R.string.please_enable_bt_device)
    }

    /**
     * 用户启用蓝牙设备成功.
     */
    protected open fun onUserEnableBlueToothSuccess(adapter: BluetoothAdapter) {
        onDeviceReady(adapter)
    }
}
